import { defineStore } from 'pinia'
import { store } from '../index'
import type { MenuItem } from '@/components/Menu/types'

export interface MenuState {
  menuData: MenuItem[]
  isMenuLoaded: boolean
}

export const useMenuStore = defineStore('menu', {
  state: (): MenuState => ({
    menuData: [],
    isMenuLoaded: false
  }),
  getters: {
    getMenuData(): MenuItem[] {
      // 确保始终返回有效的数组
      if (!this.menuData || !Array.isArray(this.menuData)) {
        console.warn('菜单数据无效，返回空数组')
        return []
      }
      return this.menuData
    },
    getIsMenuLoaded(): boolean {
      return this.isMenuLoaded
    }
  },
  actions: {
    setMenuData(menuData: MenuItem[]) {
      // 验证输入数据
      if (!menuData || !Array.isArray(menuData)) {
        console.warn('setMenuData: 输入数据无效，设置为空数组')
        this.menuData = []
        this.isMenuLoaded = false
        return
      }

      this.menuData = menuData
      this.isMenuLoaded = true
    },
    clearMenuData() {
      this.menuData = []
      this.isMenuLoaded = false
    }
  },
  persist: true
})

export const useMenuStoreWithOut = () => {
  return useMenuStore(store)
}
